<?php
class cmsdream_twitter {
	private $_params;
	
	public function __construct($params) {
		$this->_params = $params;
	}
	
	//热门话题
	public function get_twitter_hot_topics() {
		$cache = $GLOBALS['E'];
		$topics = $cache->get("twitter-hot-topics");
		if(!$topics) {
			$topics = cmsdream_tqq::api()->getHotTopic(array('type'=>1,'n'=>20,'pos'=>0));
			if(is_array($topics) && isset($topics['ret']) && $topics['ret']==0) {
				$cache->write("twitter-hot-topics", str_replace("'", "\\'", serialize($topics['data'])), (time() + $GLOBALS['C']->CACHETIME));
			}
			$topics = empty($topics['data']) ? $topics['msg'] : $topics['data'];
		}
		return $topics;
	}
	
	//名人列表
	public function get_twitter_famous() {
		$arr = array(101,102,103,104,105,106,108,109,110,111,112,114,115,267,288,
					array('id'=>294,'sub'=>array(953,955,956,957,958)),304,363,945,949,950,951,
					array('id'=>268,'sub'=>array(959,960,961,962,963,964))
				);
		$params = array('c'=>101,'s'=>null);
		$key = rand(0, count($arr) - 1);
		if(is_array($arr[$key])) {
			$key1 = rand(0, count($arr[$key]['sub']) - 1);
			$params = array('c'=>$arr[$key]['id'],'s'=>$arr[$key]['sub'][$key1]);
		} else {
			$params = array('c'=>$arr[$key],'s'=>null);
		}
		
		$cache = $GLOBALS['E'];
		$famous = $cache->get("twitter-famous-list");
		if(!$famous) {
			$famous = cmsdream_tqq::api()->getFamousList($params);
			if(is_array($famous) && isset($famous['ret']) && $famous['ret']==0) {
				$cache->write("twitter-famous-list", str_replace("'", "\\'", serialize($famous['data'])), (time() + $GLOBALS['C']->CACHETIME));
			}
			$famous = $famous['data'];
		}
		return $famous;
	}
	
	public function get_twitter_user($name) {
		$db = $GLOBALS['DB'];
		$table = $GLOBALS['C']->TABLE_PREFIX.'twitter_users';
		$user = $db->fetch("SELECT `data` FROM `$table` WHERE `name` = '{$db->e($name)}' LIMIT 1");
		if($user) {
			$user = strlen($user->data) > 1 ? unserialize($user->data) : array();
		} else {
			$user = cmsdream_tqq::api()->getUserInfo(array('n'=>$name));
			if(is_array($user) && isset($user['ret']) && $user['ret']==0) {
				$user = $user['data'];
				$_name = $db->e($user['name']);
				$_nick = $db->e($user['nick']);
				$_email = $db->e($user['email']);
				$_sex = intval($user['sex']);
				$_birthday = $user['birth_year'].'-'.$user['birth_month'].'-'.$user['birth_day'];
				$_pos = $user['country_code'].'|'.$user['province_code'].'|'.$user['city_code'];
				$_location = $db->e($user['location']);
				$_data = serialize($user);
				$_time = time();
				
				if($_email!='' || !empty($_email)) {
					$db->query("INSERT INTO `$table`(`name`,`nickname`,`email`,`sex`,`birthday`,`pos`,`location`,`data`,`time`) 
						VALUES('$_name','$_nick','$_email','$_sex','$_birthday','$_pos','$_location','$_data','$_time')");
				}
			} else {
				$user = array(
					'Ismyblack' => 0,
		            'Ismyfans]' => 0,
		            'Ismyido' => 0,
            		'birth_day' => 1,
					'birth_month' => 1,
					'birth_year' => 1900,
					'city_code' => 1,
					'country_code' => 1,
					'edu' => null,
					'email' => '',
					'fansnum' => 0,
					'head' => '',
					'idolnum' => 0,
					'introduction' => '',
					'isent' => 0,
					'ismyblack' => 0,
					'ismyfans' => 0,
					'ismyidol' => 0,
					'isvip' => 0,
					'location' => '',
					'name' => '',
					'nick' => '',
					'openid' => 0,
					'province_code' => 0,
					'sex' => 1,
					'tag' => null,
					'tweetnum' => 0,
					'verifyinfo' => 0
				);
			}
		}
		return $user;
	}
	
	public function twitter_pager() {
		$base = $this->_params['_home'] . '/' . $this->_params['_request'];
		$post = $this->_params['_posts'];
		$str = '';
		if(!$GLOBALS['Q']->is_wap) $str .= '<li>';
		if($this->_params['_pager']['f'] != 0) {
			$str .= '<a href="'.$base.'">返回第一页</a>';
			if($GLOBALS['Q']->is_wap)
			$str .= '|';
		}
		$_p = $post['info'][count($post)-1];
		$_i = isset($post['pageinfo']) ? 'i=' . $post['pageinfo'] : 't='.$_p['timestamp'].'&amp;l='.$_p['id'];
		$str .= '<a href="'.$base.'?f=1&amp;'.$_i.'">下一页</a>';
		if(!$GLOBALS['Q']->is_wap) $str .= '</li>';
		echo $str;
	}
	
	private static function url_encode($str) {
		return str_replace('+', '%20', urlencode($str));
	}
	
	public function content_format($post, $users = null, $showtime = false) {
		$content = $this->_content_format($post, $users, $showtime);
		if($GLOBALS['Q']->is_wap) {
			//<a href="http://url.cn/0owiB7" target="_blank">http://url.cn/0owiB7</a>
			$content = preg_replace('/<a[\s]+href="([^"]+)"[^>]+>[^<]+<\/a>/i', '<a href="$1" target="_blank">[链接]</a>', $content);
			$content = preg_replace('/<p[\s]+class="meta">(.*)<\/p>/i', '', $content);
			$content = preg_replace('/<p[^>]+>/i', '', $content);
			$content = preg_replace('/<\/p>/i', '<br/>', $content);
			$content = preg_replace('/<span>(.*)<\/span>/i', '<i>$1</i>', $content);
			$content = str_replace('<div class="clear"></div>', '', $content);
			$content = preg_replace('/<div[^>]+>/i', ' || ', $content);
			$content = preg_replace('/<\/div>/i', '', $content);
			$content = preg_replace(
						'/<a[^>]+href=(\'|")([^\'"]+)(\'|")[^>]+><img[^>]+src=(\'|")([^\'"]+)(\'|")[^>]+><\/a>/i',
						'<br/><img src="$5" />'."\n", $content);
		}
		return $content;
	}
	
	private function _content_format($post, $users = null, $showtime = false) {
		$txt = $post['text']; //$post['origtext'];

		if(preg_match_all('/\#([^\#]+)\#/i', $txt, $matches)) {
			foreach($matches[1] as $key => $match) {
				$txt = str_replace($matches[0][$key], '<a href="'.$this->_params['_home'].'/twitter/k/'.self::url_encode($match).'">#'.$match.'#</a>', $txt);
			}
		}

		if(preg_match_all('/@([a-zA-Z]{1}[\w\-]+)/i', $txt, $matches)) {
			foreach($matches[1] as $key => $match) {
				if(isset($users[$match])) {
					$txt = str_replace($matches[0][$key], '<a href="'.$this->_params['_home'].'/twitter/'.$match.'">'.$users[$match].'</a>', $txt);
				} else {
					$txt = str_replace($matches[0][$key], '@<a href="'.$this->_params['_home'].'/twitter/'.$match.'">'.$match.'</a>', $txt);
				}
			}
		}
		
		$str = '';
		if($showtime) $str .= '<div class="quote" id="post-'.$post['id'].'">';		
		if(!$showtime && isset($this->_params['k']) && !$GLOBALS['Q']->is_wap) {
			$str .= '<span class="headimg"><img src="'.$post['head'].'/50" /></span>';
		}
		$str .= '<a href="'.$this->_params['_home'].'/twitter/'.$post['name'].'">'.$post['nick'].'</a>: ';
		$str .= $txt;
		if(!empty($post['image'])) {
			$str .= "<p class=\"imgs\">";
			foreach($post['image'] as $img){
				$str .= '<a href="'.$img.'/2000" target="_blank"><img res="'.$img.'" src="'.$img.'/160" onclick="return imgt(this);" /></a>';
			}
			$str .= "<div class=\"clear\"></div></p>";
		}
		if(!empty($post['source'])) {
			$str .= $this->_content_format($post['source'], $users, true);
		}
		if($showtime) {
			$str .= '<p class="meta">'.$this->date_format($post['timestamp']).' 来自<span>'.$post['from'].'</span></p>';
			$str .= '</div>';
		}
		return $str;
	}
	
	public function date_format($date){
		$limit = time() - $date;
		if($limit < 60) {
			return $limit . '秒前';
		}
		if($limit >= 60 && $limit < 3600) {
			return floor($limit/60) . '分钟前';
		}
		if($limit >= 3600 && $limit < 86400) {
			return floor($limit/3600) . '小时前';
		}
		if($limit >= 86400 && $limit < 2592000) {
			return floor($limit/86400) . '天前';
		}
		if($limit >= 2592000) {
			return date('Y-m-d H:i:s', $date);
		}
	}
	
	public static function getTqq() {		
		$token = cmsdream_login::get_sc('QQWBToken', '');
		$_token = cmsdream_login::get_sc('QQWBRefreshToken', '');
		if($token=='' || $_token=='') {
			return array();
		}
		$s = explode('|', $token);
		return array('token'=>$_token,'access_token'=>$s[0],'time'=>$s[1],'name'=>$s[2],'nick'=>urldecode($s[3]));
	}
	
}

